package com.link.base.base.product.service;

import com.link.base.user.model.CoreUser;
import com.link.base.base.common.dao.mybatis.mapper.AttachmentMapper;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.mvg.dao.mybatis.product.mapper.ProductCaseMvgMapper;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.product.dao.mybatis.mapper.PortalProductCaseMapper;
import com.link.base.base.product.dao.mybatis.mapper.ProductMapper;
import com.link.base.base.product.model.PortalProductCase;
import com.link.base.base.product.model.Product;
import com.link.base.base.statistics.model.Statistics;
import com.link.base.base.statistics.service.StatisticsService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;


/**
 * 产品案例服务
 *
 * @author 路江
 * @date 2019/12/13 10:53
 */

@Service
public class PortalProductCaseServiceImpl extends BasicServiceImpl<PortalProductCase>
        implements PortalProductCaseService {

    @Resource
    private PortalProductCaseMapper portalProductCaseMapper;
    @Resource
    private AttachmentService attachmentService;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Resource
    private OrgnizationService orgnizationService;

    @Resource
    private ProductCaseMvgMapper productCaseMvgMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private StatisticsService statisticsService;

    @Override
    public BasicMapper<PortalProductCase> getBasicMapper() {
        return portalProductCaseMapper;
    }

    /**
     * 上传产品案例图片
     *
     * @author 路江
     * @date 2019/12/13 10:56
     * @param entity  案例对象，
     * @param imagefileList 上传图片对象
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void uploadImg(PortalProductCase entity, List<MultipartFile> imagefileList) throws Exception {
        if (imagefileList == null || imagefileList.size() == 0) {
            throw new ServiceException("PRODUCT-005");
        }
        if (entity.getId() == null) {
            throw new ServiceException("PUBLIC-007");
        }
        for (MultipartFile file : imagefileList) {
            if (file == null) {
                throw new ServiceException("PRODUCT-005");
            }
            Attachment attachment = new Attachment();
            // 插入附件表
            LCLogger.info().withMessageKey("uploadImg")
                    .withMessage("上传附件记录！").flush();
            // 附件上传
            attachmentService.upload(file, attachment);
            LCLogger.info().withMessageKey("uploadImg")
                    .withMessage("插入附件记录！").flush();
            // 向附件表插入附件基础信息
            attachmentService.insert(attachment);
            entity.setCaseImgId(attachment.getId());
            portalProductCaseMapper.imageUpdate(entity);
        }
    }

    /**
     * 查询案例下的案例图片列表
     *
     * @author 谭琛琨
     * @date 2019/12/13 10:57
     * @param entity  案例对象， 根据案例id
     */
    @Override
    public List<Attachment> queryCaseImgByCaseId(PortalProductCase entity) throws Exception {
        PortalProductCase portalProductCase = portalProductCaseMapper.queryById(entity);
        if (Objects.isNull(portalProductCase)) {
            throw new ServiceException("PRODUCT-006");
        }
        Attachment attachmentQuery = new Attachment();
        attachmentQuery.setTotalFlag(true);
        attachmentQuery.setPageFlag(false);
        attachmentQuery.setModuleType("noType");
        attachmentQuery.setHeadId(entity.getId());
        List<Attachment> attachmentList = attachmentService.queryByExamplePage(attachmentQuery);

        //主图
        Long caseImgId = portalProductCase.getCaseImgId();
        if (caseImgId != null) {
            attachmentList.stream().forEach(a -> {
                //主图
                if (a.getId().equals(caseImgId)) {
                    a.setIsDefault("Y");
                } else {
                    a.setIsDefault("N");
                }
            });
        }
        return attachmentList;
    }

    /**
     * 更新主图
     *
     * @author crm4
     * @date 2019/12/13 10:58
     * @param productCase  案例对象， 根据案例id
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void imageUpdate(PortalProductCase productCase) throws Exception {
        portalProductCaseMapper.imageUpdate(productCase);
    }

    /**
     * 查询产品列表以及案例正文
     *
     * @author 路江
     * @date 2019/12/13 10:58
     * @param portalProductCase  案例对象
     */
    @Override
    public PortalProductCase getportalProductCase(PortalProductCase portalProductCase) throws Exception {
        //查询案例下的案例图片列表
        portalProductCase.setAttachmentList(this.queryCaseImgByCaseId(portalProductCase));
        //查询相关产品
        Product t = new Product();
        Orgnization org = orgnizationService.queryById(UserUtil.getUser().getOrgId());
        if (org.getPriceListId() == null) {
            throw new ServiceException("ORDER-082");
        }
        t.setPriceListId(org.getPriceListId());
        t.setMvgParentId(portalProductCase.getId());
        List<Product> list = productMapper.queryRightListPage(t);
        portalProductCase.setProductList(list);
        return portalProductCase;
    }

    /**
     * 删除案例相关产品
     *
     * @author 路江
     * @date 2019/12/13 10:59
     * @param entity  案例对象
     */
    @Override
    public void deleteByProductCase(PortalProductCase entity) throws Exception {
        Mvg m = new Mvg();
        if (entity.getProdId() == null) {
            throw new Exception("产品id为空");
        }
        if (entity.getMvgParentId() == null) {
            throw new Exception("案例id为空");
        }
        m.setMvgSubsetId(entity.getProdId());
        m.setMvgParentId(entity.getMvgParentId());
        productCaseMvgMapper.deleteById(m);
    }

    
    /**
     * 新增案例相关产品
     *
     * @author 谭琛琨
     * @date 2019/12/13 11:00
     * @param entity  案例对象
     */
    @Override
    public void insertProductCase(PortalProductCase entity) throws Exception {
        Mvg m = new Mvg();
        //获取id
        Long receptionId = keyGenerateDao.keyGenerate();
        m.setId(receptionId);
        m.setMvgParentId(entity.getMvgParentId());
        m.setMvgSubsetId(entity.getProdId());
        productCaseMvgMapper.insert(m);
    }

    /**
     * 通过headID删除附件
     *
     * @author 谭琛琨
     * @date 2019/12/13 11:02
     * @param entity  案例对象
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteById(PortalProductCase entity) throws Exception {
        beforDelete(entity);
        checkId(entity);
        //删除附件
        Attachment att = new Attachment();
        att.setHeadId(entity.getId());
        attachmentService.deleteByHeadId(att);
        //删除案例中间表
       /* ProductCase pc = new ProductCase();
        pc.setCaseId(entity.getId());
        productCaseService.deleteByCaseId(pc);*/
        //删除自身
        getBasicMapper().deleteById(entity);
        /**
         * @author huanglongjian
         * @2017年12月28日
         */
        afterDelete(entity);
    }

    /**
     * 重写upsert
     *
     * @author 路江
     * @date 2019/12/13 11:03
     * @param entity  案例对象
     */
    @Override
    public void upsert(PortalProductCase entity) throws Exception {
        CoreUser user = UserUtil.getUser();
        //更新附件内容
        if (entity.getAttachmentList() != null && "GUIDE_APP".equalsIgnoreCase(user.getLoginType())) {
            for (Attachment attachment : entity.getAttachmentList()) {
                attachmentMapper.update(attachment);
            }
        }
        super.upsert(entity);
    }

    /**
     * 根据产品id查询与之相关联的案例集合
     *
     * @author 单建平
     * @date 2019/12/13 11:10
     * @param record  案例对象
     */
    @Override
    public List<PortalProductCase> queryByProductId(PortalProductCase record) throws Exception {
        return portalProductCaseMapper.queryByProductId(record);
    }


    /**
     * 获取知识库的浏览量、点赞量、收藏量、当前用户是否点赞、是否收藏
     *
     * @author 欧阳振强
     * @date 2019/12/13 11:11
     * @param record  案例对象
     * @param userId  用户Id
     */
    @Override
    public void setStatisticsData(PortalProductCase record, Long userId) throws Exception {
        // 从Redis中获取知识库的浏览量、阅读人数、点赞量、收藏量
        Statistics statistics = statisticsService.getStatisticsByModuleRecord("caseBase", record.getId());
        record.setCollNum(statistics.getCollectNum());
        record.setPageviews(statistics.getPageViewNum());
        record.setThumbUpNum(statistics.getThumbNum());
        record.setReadNum(statistics.getReadNum());
        // 从Redis中获取用户是否点赞、是否收藏
        if (userId != null) {
            statistics = statisticsService.getFlagByModuleAndUser("caseBase", record.getId(), userId);
            record.setIsColl(statistics.getIsCollect());
            record.setIsThumbUp(statistics.getIsThumb());
        }
    }

    /**
     * 根据案例id查询案例详情（分享）
     *
     * @author 谭琛琨
     * @date 2019/12/13 10:51
     * @param record  案例对象
     */
    @Override
    public PortalProductCase queryByCasebaseId(PortalProductCase record) throws Exception {
        return portalProductCaseMapper.queryByCasebaseId(record);
    }

    /**
     * 根据案例id查询案例详情图片（分享）
     *
     * @author 谭琛琨
     * @date 2019/12/13 10:51
     * @param record  案例对象
     * @param org  组织对象
     */
    @Override
    public PortalProductCase queryCasebaseImg(PortalProductCase record, Orgnization org) throws Exception {
        record.setAttachmentList(this.queryCaseImgByCaseId(record));
        Product t = new Product();
        t.setPriceListId(org.getPriceListId());
        t.setMvgParentId(record.getId());
        t.setLoginCorpId(record.getCorpid());
        List<Product> list = productMapper.queryRightListPage(t);
        record.setProductList(list);
        return record;
    }
}
